package DML;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import DuiXiang.TableModel;

public class InsertTable {

	@SuppressWarnings("finally")
	public static int InsertIntoTable(String dataBaseName, String tableName, String[] fields, String[] values) {
		String dbfpath = "D:\\database\\" + dataBaseName + "\\"+ tableName + ".dbf";
		String datpath = "D:\\database\\" + dataBaseName + "\\"+ tableName + ".dat";
		List<String> fieldsList = new ArrayList<String>(fields.length);//把String[]转化成ArrayList
		List<TableModel> tableModelList = util.ReadTableModelList(dbfpath);//获取表的字段信息
		if(tableModelList==null)
			return -1;
		boolean containKey=true;
		boolean ok;
		for(String str:fields){//检查插入字段是否存在
			for(TableModel tm:tableModelList){
				ok=true;
				if(!tm.getsFieldName().equals(str)){
					ok=false;
					break;
				}
				if(!ok)
					return -2;
			}
		}
		for(String str:fields){
			for(TableModel tm:tableModelList)//检查插入字段是否含有主键
				if(tm.getsFieldName().equals(str) && tm.getbKey()+""=="y"){
					containKey=true;
					break;
				}
			fieldsList.add(str);
		}
		if(!containKey)
			return -5;
		for(TableModel tm:tableModelList){//检查是否存在不为空但未插入的字段
			if((!fieldsList.contains(tm.getsFieldName())) && tm.getbNullFlag()+""=="y")
				return -5;
		}
		if(util.IfPrimarykeyExist(values,tableModelList,datpath))//如果插入的主键值已经存在
			return -6;
		
		//将数据插入文件
		FileWriter fileWriter = null;
		BufferedWriter bufferWriter = null;
		try {
			fileWriter = new FileWriter(datpath,true);
			bufferWriter = new BufferedWriter(fileWriter);
			StringBuilder aline = new StringBuilder();
			int i,j=0;
			for(i=0;i<tableModelList.size();i++){
				if(tableModelList.get(i).getsFieldName().equals(fields[j])){
					aline.append(values[j]);
					j++;
				}
				if(i<tableModelList.size()-1)
					aline.append(",");
			}
			bufferWriter.write(aline.toString());
			bufferWriter.newLine();
			bufferWriter.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		} finally {
			try {
				bufferWriter.close();
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return 1;
		}
	}
}
